﻿using MediatR;
using T.Basic.Domain.T.Basic.Dto;
using T.Basic.Domain.T.Basic.Model;
using T.Basic.Read.API.Appliction.Command.CargoOwnerCommand;
using T.Basic.Read.API.Appliction.Command.LineCommand;
using T.Basic.Repository.BasicInterface;

namespace T.Basic.Read.API.Appliction.CommandHandlers.CargoOwnerCommandHanders
{
    public class CargoOwnerListCommandHandler : IRequestHandler<CargoOwnerListCommand, PageDto<CargoOwner>>
    {
        private readonly ICargoOwnerRepository _CargoOwnerrepository;
        public CargoOwnerListCommandHandler(ICargoOwnerRepository cargoOwnerrepository)
        {
            _CargoOwnerrepository = cargoOwnerrepository;
        }

        public async Task<PageDto<CargoOwner>> Handle(CargoOwnerListCommand request, CancellationToken cancellationToken)
        {
            PageDto<CargoOwner> pageDto = new PageDto<CargoOwner>();
            var CargoOwnerList = await _CargoOwnerrepository.GetAsync(d=>!d.IsDeleted);
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                CargoOwnerList = CargoOwnerList.Where(d => d.CompanyID == request.CompanyID).ToList();
            }
            if (!string.IsNullOrEmpty(request.CargoOwnerName))
            {
                CargoOwnerList= CargoOwnerList.Where(d=>d.CargoOwnerName.Contains(request.CargoOwnerName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.CargoOwnerPhone))
            {
                CargoOwnerList = CargoOwnerList.Where(d => d.CargoOwnerPhone.Contains(request.CargoOwnerPhone)).ToList();
            }
            if (request.DriverLicenseDate!=null)
            {
                CargoOwnerList = CargoOwnerList.Where(d => d.DriverLicenseDate == request.DriverLicenseDate).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = CargoOwnerList.Count();
            }
            var size = request.PageSize;
            var index = request.PageIndex;
            pageDto.TotalCount = CargoOwnerList.Count();
            pageDto.PageCount = (int)Math.Ceiling(pageDto.PageCount * 1.0 / (int)size);
            pageDto.list = CargoOwnerList.OrderByDescending(d => d.CreatedDate).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return pageDto;
            //pageDto.TotalCount = CargoOwnerList.Count();
            //pageDto.PageCount = (int)Math.Ceiling(pageDto.TotalCount * 1.0 /request.PageSize);
            //pageDto.list = CargoOwnerList.OrderByDescending(d => d.CreatedDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            //return pageDto;
        }
    }
}
